package com.lp.sys.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.iframework.commons.util.SFtpUtil;
import org.iframework.commons.util.fast.D;
import org.iframework.commons.util.fast.L;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.lp.sys.conf.Conf;

/**
 * 文件上传管理控制器
 * 
 * @author lp
 * 
 */
@Controller
@RequestMapping("/admin/upload")
public class UploadController {

	@RequestMapping(value = "/uploadImg.do")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
    	JSONObject resultjson = new JSONObject();
    	resultjson.put("success", 1);
    	resultjson.put("msg", "");
    	resultjson.put("file", "");
    	
    	//资源访问基本路径
    	String fileAccessBasePath = Conf.BASE_RES_PATH + Conf.IMG_SAVE_PATH;
    	//资源文件相对路径文件夹名
    	String filePath = D.format(new Date(), "yyyy-MM-dd");
    	//资源保存目录
    	String fileSavePath = Conf.IMG_BASE_PATH + Conf.IMG_SAVE_PATH + filePath + "/";
        
        if(file==null){
        	resultjson.put("success", 0);
          	resultjson.put("msg", "file为空！");
        }else{
        	  if(file.getOriginalFilename().indexOf(".")<1){
              	resultjson.put("success", 0);
              	resultjson.put("msg", "文件格式不对！");
              }else{
          		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
          		//资源文件名
          		String fileName = D.format(new Date(), "yyyyMMdd") + String.valueOf(System.currentTimeMillis()).substring(7) +suffix;
          		try {
          			L.i("上传文件："+fileSavePath + fileName);
					boolean result = SFtpUtil.upload(fileSavePath, fileName,file.getInputStream());
					if (result) {
						resultjson.put("success", 1);
	                   	resultjson.put("file", fileAccessBasePath + filePath +"/"+fileName);
	                  	resultjson.put("msg", "上传成功");
					} else {
						resultjson.put("success", 0);
	                  	resultjson.put("msg", "上传出错");
					}
				} catch (IOException e1) {
					e1.printStackTrace();
					resultjson.put("success", 0);
                  	resultjson.put("msg", "上传出错");
				}
          		
              }	
        }
      		
        return resultjson.toString();
    }
}
